<script setup lang="js">
import {ref, onMounted, watch, computed} from "vue";
import { useRoute } from "vue-router";
import {Search} from "@element-plus/icons-vue";
import {getCoupon,couponHistoryList} from "@/api/coupon.js";

const route = useRoute();
const defaultTypeOptions = [
  {
    label: '全场赠券',
    value: 0
  },
  {
    label: '会员赠券',
    value: 1
  },
  {
    label: '购物赠券',
    value: 2
  },
  {
    label: '注册赠券',
    value: 3
  }
];
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  useStatus: null,
  orderSn: null,
  couponId: null
};
const defaultUseTypeOptions= [
  {
    label: "未使用",
    value: 0
  },
  {
    label: "已使用",
    value: 1
  },
  {
    label: "已过期",
    value: 2
  }
];

const listQuery = Object.assign({}, defaultListQuery);
const useTypeOptions = Object.assign({}, defaultUseTypeOptions);
const checkForm = ref({});
const coupon = ref({});
const couponList = ref([]);
const total = ref(0);
const couponHistoryTable = ref('');

// 格式化优惠券类型
const formatType = (type) => {
  for (let i = 0; i < defaultTypeOptions.length; i++) {
    if (type === defaultTypeOptions[i].value) {
      return defaultTypeOptions[i].label;
    }
  }
  return '';
}

// 格式化可使用商品
const formatUseType = (useType) => {
  if(useType===0){
    return '全场通用';
  }else if(useType===1){
    return '指定分类';
  }else{
    return '指定商品';
  }
}

// 格式化时间
const formatDate = (date) => {
  // 检查是否为 Date 对象
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
const formatTime = (time) => {
  if (!(time instanceof Date)) {
    time = new Date(time);
  }
  const year = time.getFullYear();
  const month = String(time.getMonth() + 1).padStart(2, '0');
  const day = String(time.getDate()).padStart(2, '0');
  const hour = String(time.getHours()).padStart(2, '0');
  const minute = String(time.getMinutes()).padStart(2, '0');
  const second = String(time.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

// 格式化状态
const formatStatus = (endTime) => {
  let now = new Date().getTime();
  let endDate = new Date(endTime);
  if(endDate>now){
    return '未过期'
  }else{
    return '已过期';
  }
}

// 格式化获取方式
const formatGetType = (type) => {
  if(type===1) {
    return '主动获取';
  } else {
    return '推广赠送';
  }
}

// 格式化优惠券使用状态
const formatCouponHistoryUseType = (useType) =>{
  if (useType === 0) {
    return '未使用';
  } else if (useType === 1) {
    return '已使用';
  } else {
    return '已过期';
  }
}

onMounted(() => {
  getCoupon(route.query.id).then(res => {
    coupon.value = res.data.data;
  })
  listQuery.couponId=route.query.id;
  getCouponHistoryList();
})

//TODO: 获取优惠券列表
const getCouponHistoryList = async () => {
  couponHistoryList(listQuery).then(res => {
    couponList.value = res.data.data.list;
    total.value = res.data.data.total;
  })
}

//TODO: 查询搜索
const handleSearchList = () => {
  listQuery.pageNum = 1;
  listQuery.useStatus = checkForm.value.useStatus;
  listQuery.orderSn = checkForm.value.orderSn;
  listQuery.couponId = route.query.id;
  console.log(checkForm.value);
  getCouponHistoryList();
}

//TODO: 重置搜索
const handleResetSearch = () => {
  checkForm.value = defaultListQuery;
  listQuery.couponId = route.query.id;
  getCouponHistoryList();
}

// 监听listQuery变化，同步到checkForm
watch(() => listQuery, (newVal) => {
      checkForm.value = newVal
    },
    {immediate: true}
)
// TODO: 分页操作方法
const handleSizeChange = (size) => {
  listQuery.pageNum = 1;
  listQuery.pageSize = size;
  getCouponHistoryList()
}
const handleCurrentChange = (val) => {
  listQuery.pageNum = val;
  getCouponHistoryList();
}

</script>

<template>
  <div class="check-list">
    <!-- 优惠券信息 -->
    <div class="table-layout">
      <el-row>
        <el-col :span="4" class="table-cell-title">名称</el-col>
        <el-col :span="4" class="table-cell-title">优惠券类型</el-col>
        <el-col :span="4" class="table-cell-title">可使用商品</el-col>
        <el-col :span="4" class="table-cell-title">使用门槛</el-col>
        <el-col :span="4" class="table-cell-title">面值</el-col>
        <el-col :span="4" class="table-cell-title">状态</el-col>
      </el-row>
      <el-row>
        <el-col :span="4" class="table-cell">{{ coupon.name}}</el-col>
        <el-col :span="4" class="table-cell">{{formatType(coupon.type)}}</el-col>
        <el-col :span="4" class="table-cell">{{formatUseType(coupon.useType)}}</el-col>
        <el-col :span="4" class="table-cell">满{{coupon.minPoint}}元可用</el-col>
        <el-col :span="4" class="table-cell">{{coupon.amount}}元</el-col>
        <el-col :span="4" class="table-cell">{{formatStatus(coupon.endTime)}}</el-col>
      </el-row>
      <el-row>
        <el-col :span="4" class="table-cell-title">有效期</el-col>
        <el-col :span="4" class="table-cell-title">总发行量</el-col>
        <el-col :span="4" class="table-cell-title">已领取</el-col>
        <el-col :span="4" class="table-cell-title">待领取</el-col>
        <el-col :span="4" class="table-cell-title">已使用</el-col>
        <el-col :span="4" class="table-cell-title">未使用</el-col>
      </el-row>
      <el-row>
        <el-col :span="4" class="table-cell" style="font-size: 13px">
          {{formatDate(coupon.startTime)}} 至 {{formatDate(coupon.endTime)}}
        </el-col>
        <el-col :span="4" class="table-cell">{{coupon.publishCount}}</el-col>
        <el-col :span="4" class="table-cell">{{coupon.receiveCount}}</el-col>
        <el-col :span="4" class="table-cell">{{coupon.publishCount-coupon.receiveCount}}</el-col>
        <el-col :span="4" class="table-cell">{{coupon.useCount}}</el-col>
        <el-col :span="4" class="table-cell">{{coupon.publishCount-coupon.useCount}}</el-col>
      </el-row>
    </div>
    <!-- 筛选搜索 -->
    <el-card class="filter-container" shadow="never">
      <div class="search-container">
        <div class="search-title">
          <el-icon><Search /></el-icon>
          <span style="margin-left: 10px">筛选搜索</span>
        </div>
        <div class="search-btn">
          <el-button
              icon="search"
              type="primary"
              @click="handleSearchList()">
            查询搜索
          </el-button>
          <el-button
              icon="refresh"
              @click="handleResetSearch()">
            重置
          </el-button>
        </div>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="checkForm" label-width="120px">
          <el-form-item label="使用状态：">
            <el-select v-model="checkForm.useStatus" placeholder="全部" class="input-width" clearable >
              <el-option v-for="item in useTypeOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单编号：">
            <el-input v-model="checkForm.orderSn" placeholder="订单编号" class="input-width" clearable ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- 优惠券使用记录表格 -->
    <div class="table-container">
      <el-table ref="couponHistoryTable"
                :data="couponList"
                style="width: 100%;" border>
        <el-table-column label="优惠码"  align="center">
          <template #default="{row}">{{row.couponCode}}</template>
        </el-table-column>
        <el-table-column label="领取会员"  align="center">
          <template #default="{row}">{{row.memberNickname}}</template>
        </el-table-column>
        <el-table-column label="领取方式"  align="center">
          <template #default="{row}">{{formatGetType(row.getType)}}</template>
        </el-table-column>
        <el-table-column label="领取时间"  align="center">
          <template #default="{row}">{{formatTime(row.createTime)}}</template>
        </el-table-column>
        <el-table-column label="当前状态"  align="center">
          <template #default="{row}">{{formatCouponHistoryUseType(row.useStatus)}}</template>
        </el-table-column>
        <el-table-column label="使用时间"  align="center">
          <template #default="{row}">{{row.useTime===null?'N/A':formatTime(row.useTime)}}</template>
        </el-table-column>
        <el-table-column label="订单编号" align="center">
          <template #default="{row}">{{row.orderSn===null?'N/A':row.orderSn}}</template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-bar">
      <el-pagination
          background
          layout="total, sizes,prev, pager, next,jumper"
          :total="total"
          :page-sizes="[5,10,15,20]"
          v-model:page-size="listQuery.pageSize"
          v-model:current-page="listQuery.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<style scoped>

.check-list {
  width: 100%;
  height: 100%;
}

.table-layout {
  margin-top: 20px;
  border-left: 1px solid #DCDFE6;
  border-top: 1px solid #DCDFE6;
}

.table-cell {
  height: 60px;
  line-height: 40px;
  border-right: 1px solid #DCDFE6;
  border-bottom: 1px solid #DCDFE6;
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  overflow: hidden;
}

.table-cell-title {
  border-right: 1px solid #DCDFE6;
  border-bottom: 1px solid #DCDFE6;
  padding: 10px;
  background: #F2F6FC;
  text-align: center;
  font-size: 14px;
  color: #303133;
}

.filter-container {
  margin-top: 20px;
}

.search-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}

.search-title {
  padding: 0 10px;
  display: flex;
  align-items: center;
}

.input-width{
  width: 300px;
}

.table-container {
  margin-top: 20px;
}

.page-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;

}

</style>